<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="top_header_left">
      </div>
      <div class="top_header_right">
        <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 20px"
          @click="dialogFormVisible1 = true;">
          新增
        </el-button>
      </div>
    </div>

    <el-table ref="multipleTable" :data="list" stripe style="width: 1200px" border>
      <el-table-column prop="id" label="id" width="80" align="center" :show-overflow-tooltip='true' />
      <el-table-column prop="name" label="名称" align="center" :show-overflow-tooltip='true' />
      <el-table-column prop="pic_full" label="封面图" width="200" align="center">
        <template align="center" slot-scope="scope">
          <div class="demo-image__preview">
            <el-image class="my-img" :src="scope.row.pic_full" ref="myImg" :preview-src-list="srcList"
              @click="handlePriveImg(scope.row.pic_full)" @click.stop="handleClickItem">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" align="center" />
      <el-table-column prop="is_show" label="是否显示" align="center">
        <template align="center" slot-scope="scope">
          <span v-if="scope.row.is_show == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template align="center" slot-scope="scope">
          <el-button type="button" size="small"
            @click="atlas = {...scope.row};atlas.is_show=atlas.is_show+'';dialogFormVisible1 = true;">
            编辑
          </el-button>
          <el-button type="button" size="small" @click="setUp(scope.row)">
            设置礼物
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="pageSize"
      @pagination="handleFilter" /> -->

    <el-dialog :title="atlas.id?'编辑':'新增'" :visible.sync="dialogFormVisible1" style="width:800px;margin:0 auto;"
      class="model_">
      <div class="center_lisr">
        <div>
          <span>图鉴名称</span>
          <el-input v-model="atlas.name" placeholder="图鉴名称" style="width:300px;max-width:70%;" />
        </div>
        <div>
          <span>封面图</span>
          <div style="width:70%;height:100px">
            <div class="image_new_100">
              <img v-if="atlas.pic_full" :src="atlas.pic_full" alt="">
              <el-upload class="upload-demo" action="http://testapi2.xunyinjiaoyou.com/record/uploadImg"
                :on-remove="handleRemove" :before-remove="beforeRemove" multiple :on-exceed="handleExceed"
                :file-list="fileList" :http-request="uploadFile" ref="upload" :on-change="onchange">
                <el-button size="small" type="primary">{{atlas.pic_full?'点击替换':'点击上传'}}</el-button>
              </el-upload>
            </div>

          </div>
        </div>
        <div>
          <span>排序</span>
          <el-input v-model="atlas.sort" placeholder="排序" style="width:300px;max-width:70%;" type="number" />
        </div>
        <div>
          <span>是否显示</span>
          <div style="width:300px;max-width:70%;display:flex;">
            <el-radio v-model="atlas.is_show" label="1">是</el-radio>
            <el-radio v-model="atlas.is_show" label="0">否</el-radio>
          </div>
        </div>
        <div>
          <el-button class="filter-item" type="primary" style="width:100%;margin:0 auto;margin-top:10px"
            @click="giftAdd">
            保存
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import {
    encryption2
  } from "@/api/index";
  export default {
    name: "ComplexTable",
    components: {
      Pagination,
    },
    data() {
      return {
        pageSize:10,
        page:1,
        total: '',
        calendarTypeOptions1: [],
        list: [],
        time_list: {},
        atlas: {
          name: '',
          pic: '',
          pic_full: '', //完整路径
          sort: '',
          is_show: '1',
        },
        dialogFormVisible1: false,
        srcList: [],
        fileList: [],
      };
    },
    watch: {
      dialogFormVisible1: {
        handler(newName, oldName) {
          if (!newName) {
            this.atlas = {
              name: '',
              pic: '',
              pic_full: '', //完整路径
              sort: '',
              is_show: '1',
            };
            this.$refs.upload.clearFiles();
          }
        },
        deep: true
      }
    },
    created() {
      this.handleFilter();
    },

    methods: {
      giftAdd() {
        if (this.atlas.id) {
          this.editgift() //编辑
        } else {
          this.addgift() //添加
        }
      },
      // 添加
      addgift() {
        const arys = {
          name: this.atlas.name,
          pic: this.atlas.pic,
          sort: this.atlas.sort,
          is_show: this.atlas.is_show,
        };
        const url = "/gift/giftCollectAdd";
        encryption2(arys, url).then((res) => {
          if (res.data.status === 0) {
            this.handleFilter();
            this.$message({
              message: res.data.text,
              type: "success",
            });
            this.$refs.upload.clearFiles()
            this.dialogFormVisible1 = false;
          } else {
            this.$message({
              message: res.data.text,
              type: "error",
            });
          }
        });
      },
      // 编辑
      editgift() {
        const arys = {
          id: this.atlas.id,
          name: this.atlas.name,
          pic: this.atlas.pic,
          sort: this.atlas.sort,
          is_show: this.atlas.is_show,
        };
        const url = "/gift/giftCollectEdit";
        encryption2(arys, url).then((res) => {
          if (res.data.status === 0) {
            this.handleFilter();
            this.$message({
              message: res.data.text,
              type: "success",
            });
            this.$refs.upload.clearFiles()
            this.dialogFormVisible1 = false;
          } else {
            this.$message({
              message: res.data.text,
              type: "error",
            });
          }
        });
      },
      handleRemove(file, fileList) {
        this.atlas.pic = '',
          console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件`);
        // this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      onchange(file, fileList) {
        if (fileList.length > 1) {
          fileList.splice(0, 1);
        }
        // console.log(URL.createObjectURL(file.raw));
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      uploadFile(param) {
        var that = this; //避免this指针在后面的请求以后改变
        var fileObj = param.file;
        // this.uploadAction是接收上传文件的后台地址
        var FileController = "http://testadmin-api.xunyinjiaoyou.com/admin/imgUpload";
        // FormData 对象
        var forms = new FormData();
        // 文件对象
        forms.append("img_file", fileObj);
        // XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();
        xhr.open("post", FileController, true);
        xhr.onload = function () {
          var strData = xhr.response; //回传的数据接受
          var jsonData = JSON.parse(strData); //这里由于后端接口返回的是String，而后面需要的是json
          that.atlas.pic_full = jsonData.result.full_url; //取出json中对应需要的数据存入form表单中
          that.atlas.pic = jsonData.result.url; //取出json中对应需要的数据存入form表单中
        };
        xhr.send(forms);
      },
      handlePriveImg(row) {
        this.srcList = []
        this.srcList.push(row); //将后端的这一行的数据push进数组中
        this.$refs.myImg.clickHandler();
      },
      // 获取图片遮罩层dom
      handleClickItem() {
        setTimeout(function () {
          let domImageMask = document.querySelector(".el-image-viewer__wrapper");
          if (!domImageMask) {
            return;
          }
          domImageMask.addEventListener("click", (e) => {
            if (e.target.parentNode.className == 'el-image-viewer__actions__inner' || e.target.parentNode
              .className == 'el-image-viewer__btn el-image-viewer__next' || e.target.parentNode.className ==
              'el-image-viewer__btn el-image-viewer__prev') {
              return; //如果点击底部菜单，不关闭
            }
            // 点击遮罩层时调用关闭按钮的 click 事件
            document.querySelector(".el-image-viewer__close").click();
            document.querySelector('body').setAttribute('style', 'overflow:auto;')
          });
        }, 300)
      },

      setUp(row) {
        this.$router.push({
          path: '/gift_mg/setUp',
          name: 'setUp',
          params: {
            row: row
          }
        })
      },
      // 查询
      handleFilter() {
        const arys = {
          page:this.page
        };
        const url = "/gift/giftCollectList";
        encryption2(arys, url).then((res) => {
          if (res.data.status === 0) {
            this.list = res.data.result.list;
            this.total = res.data.result.total;
          } else {
            this.$message({
              message: res.data.text,
              type: "error",
            });
          }
        });
      },
    },
  };
</script>
<style scoped>
  .filter-container .filter-item {
    margin-bottom: 0;
  }

  .el-table--border {
    border-right: 1px solid #dfe6ec;
  }

  .el-alert {
    width: 1200px;
  }

  .filter-container {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 1200px;
  }

  .batch {
    width: 1200px;
    margin: 10px 0;
    display: flex;
    flex-direction: row-reverse;
  }

  .batch .filter-item {
    margin-left: 20px;
  }

  .el-dialog {
    width: 300px;
    height: 300px;
  }

  .center_lisr {
    width: 96%;
    height: 80%;
    margin: auto;
    display: flex;
    flex-direction: column;
    align-items: center;


  }

  .flex_de>div {
    display: flex;
    flex-direction: column;
  }

  .center_lisr>div {
    display: flex;
    width: 100%;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
  }

  .center_lisr>div>el-input {
    flex: 1;
    margin-left: 20px;
  }

  .model_ /deep/ .el-dialog__body {
    padding-top: 0%;
  }

  .model_ /deep/ .el-button--mini {
    padding: 10px 20px;
  }

  .model_ /deep/ .el-dialog {
    border-radius: 4px;
  }

  .model_ /deep/ .el-input__inner {
    /* text-align: center; */
  }

  .flex_de /deep/ .el-input__inner {
    padding: 0 4px;
    border: 0;
    background: 00000000;
  }

  .new_row {
    width: 80%;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #333;
    font-weight: blod;
    font-family: serif;
    cursor: pointer;
  }

  .my-img {
    width: 80px;
    /* height: 80px; */
    padding: 10px;
    margin-right: auto;
  }

  .image_new_100 {
    height: 100px;
    display: flex;
    align-items: center;
  }

  .image_new_100>img {
    width: 50px;
    margin-right: 10px;
  }
  .demo-image__preview{

  }
</style>